Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

223
Visualizações
What is the difference between "?" and "= null" in PHP function parameters

I was doing some research but wasn't able to find an answer (probably beacause I did not searched it right)

Consider this piece of code:

public function foo(?array $optionalParam);

And then this one:

public function foo(array $optionalParam = null);

What differs between them? Using PHPstorm I noticed that when I use the ?, it creates a PHPdoc and mark the variable type as type|null. But when I call the function without that argument, PHP screams on my face "you kidding me? where is $optionalParam". In the other side, I managed to use with no problems the =null option.

Sorry if this question is too simple, but i did not find any answers online.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

First of all, the ? goes before the type, not after... other than this:

Using

public function foo(?array $optionalParam);

you are forced to pass something, that can be either null or an array, infact:

<?php
function foo(?array $optionalParam){
  echo "test";
}

foo(); // doesn't work
foo(null); // works
foo([]); // works

where instead using

public function foo(array $optionalParam = null);

will accept null, an array, or 0 parameters

<?php
function foo(array $optionalParam = null){
  echo "test";
}

foo(null); // works
foo(); // work
foo([]); // works
over 4 years ago · Santiago Trujillo Relatório

0

It's a PHP 7.1 feature called Nullable Types

Both of the lines you wrote are identical.

array ?$optionalParam : either an array or null

array $optionalParam = null : either an array or null

Tho using ? you'd still need to add the parameter when calling the function.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda